package com.icesoft.system.safe.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/**
 * 获取cipher，注意cipher不是线程安全的
 */
public class CipherUtils {

	public static byte[] doFinal(Cipher cipher, byte[] data) throws IllegalArgumentException {
		try {
			return cipher.doFinal(data);
		} catch (IllegalBlockSizeException e) {
			throw new IllegalArgumentException("解密错误", e);
		} catch (BadPaddingException e) {
			throw new IllegalArgumentException("密钥错误", e);
		}
	}

	public static Cipher getCipher(String transformation, Key key, int mode) {
		try {
			Cipher cipher = Cipher.getInstance(transformation);
			cipher.init(mode, key);
			return cipher;
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException("无此解密算法", e);
		} catch (NoSuchPaddingException e) {
			throw new IllegalArgumentException("NoSuchPaddingException", e);
		} catch (InvalidKeyException e) {
			throw new IllegalArgumentException("系统未支持，请联系管理员", e);
		}

	}
}
